from utils.database_table import RoadTable
import geopandas as gpd
import shapely 
import settings
import numpy as np 
import pandas as pd
import os,sys

def _hectometer_stake(fuse_table,road_data:gpd.GeoSeries)->gpd.GeoDataFrame:
    # 获取起点桩号与终点桩号
    qdzh = road_data[fuse_table.start_stake] * 10
    zdzh = road_data[fuse_table.end_stake] * 10
    geometry = road_data[fuse_table.geom]
    ldbm = road_data[fuse_table.segment_code] 
    
    # 内插桩号存储
    zhs_100 = []
    for i in range(int(np.floor(qdzh)) + 1,int(np.floor(zdzh)) + 1):
        interpolate_zh = i
        inter_length = (interpolate_zh - qdzh) / (zdzh - qdzh) * geometry.length
        zhs_100.append([geometry.interpolate(inter_length),i / 10, ldbm])
    #     print(inter_length)
    zhs_df = gpd.GeoDataFrame(pd.DataFrame(zhs_100,columns=['geom','zh','ldbm']),geometry = 'geom')
    
    return zhs_df

def hectometer_stake_layer(HECTOR_STAKE_PREFIX, fuse_table:RoadTable):
    ## TODO 还需要考虑一下方向问题 20210820
    ## 考虑方向 是不是已经修改geom了？
    dataLayer = gpd.read_postgis(con = settings.conn,sql = f"select * from {fuse_table.name}")
    zhs_100_all_df = None
    for i in range(len(dataLayer)):
        road_data = dataLayer.iloc[i]
        zhs_100_df = _hectometer_stake(fuse_table,road_data)
        if(zhs_100_all_df is None):
            zhs_100_all_df = zhs_100_df
        else:
            zhs_100_all_df = zhs_100_all_df.append(zhs_100_df)
    if(zhs_100_all_df is not None):
        zhs_100_all_df = zhs_100_all_df.reset_index(drop=True)
        zhs_100_all_df.set_crs(f'epsg:{settings.SRID}', inplace=True )
        zhs_100_all_df.to_postgis(f"{HECTOR_STAKE_PREFIX}_{fuse_table.name}",
                      settings.engine,
                      if_exists='replace')
    print(f"{fuse_table.name}百米桩内插完成")
    return zhs_100_all_df

def hectometer_stake_line(fuse_table:RoadTable,ldbm = None, geom = None):
    dataGeom_df = gpd.read_postgis(f"select * from {fuse_table.name} where ldbm = {ldbm}")
    if len(dataGeom_df) == 0:
        print("输入路段编号不存在，请检查后重新输入。")
        raise ValueError("输入路段编号不存在，请检查后重新输入。")
    dataGeom = dataGeom_df.iloc[0].geom
    _hectometer_stake(fuse_table,dataGeom)